package com.emm.yixun.marketing.service.impl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.ImageService;
import com.emm.yixun.basic.service.MortgageRecordFollowService;
import com.emm.yixun.basic.service.MortgageRecordService;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.MortgageRecord;
import com.emm.yixun.common.model.dto.ImageDto;
import com.emm.yixun.common.model.dto.MortgageRecordDto;
import com.emm.yixun.common.model.dto.MortgageRecordFollowDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.ImgTypeEnum;
import com.emm.yixun.common.model.enums.ProcessStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.marketing.service.MortgageRecordServiceFacade;

@Service("mortgageRecordServiceFacade")
@WebService(name="com.emm.yixun.marketing.service.MortgageRecordServiceFacade")
public class MortgageRecordServiceFacadeImpl implements MortgageRecordServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private MortgageRecordService service;
	@Autowired
	private MortgageRecordFollowService mortgageRecordFollowService;
	@Autowired
	private ImageService imageService;
	@Autowired
	private DataPermissionService dataPermissionService;

	@Override
	public Response<MortgageRecordDto> save(MortgageRecordDto dto) {
		Response<MortgageRecordDto> response=new Response<MortgageRecordDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			MortgageRecordDto mDto=service.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(MortgageRecordDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			MortgageRecordDto mDto=new MortgageRecordDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<MortgageRecord> findById(Long id) {
		Response<MortgageRecord> response=new Response<MortgageRecord>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			MortgageRecord entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<MortgageRecord> findByDto(MortgageRecordDto dto) {
		ResponseList<MortgageRecord> response=new ResponseList<MortgageRecord>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<MortgageRecord> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<MortgageRecord> findPageByDto(MortgageRecordDto dto, Integer begin,Integer row) {
		Page<MortgageRecord> response=new Page<MortgageRecord>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<MortgageRecord> page = service.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<MortgageRecordDto> findPageDtoByDto(MortgageRecordDto dto,
			Integer begin, Integer row) {
		Page<MortgageRecordDto> response = new Page<MortgageRecordDto>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			
			//数据权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), dto.getPrefix(), dto.getColumnName());
				String [] dataPermissionArr = dataPermission.split(":");
				if("00".equals(dataPermissionArr[0])){
					response.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					response.setSuccess(false);
					return response;
				}
				dto.setDataPermission(dataPermissionArr[1]);
			}
			
			Page<MortgageRecordDto> page = service.getPageDtoModel(dto, begin, row);
			page.setPageSize(row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<MortgageRecordDto> findMortgageDetail(MortgageRecordDto dto) {
		Response<MortgageRecordDto> response=new Response<MortgageRecordDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			MortgageRecordDto mortgageRecordDto = service.selectMortgageDetailByDto(dto);
			if(null == mortgageRecordDto){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(mortgageRecordDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}
	
	@Override
	public Map<String, String> addMortgageFollow(MortgageRecordDto dto) {
		Map<String, String> returnMap = new HashMap<String, String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try{
			MortgageRecord mortRecord = null;
			if(dto.getId() != null){
				mortRecord = service.selectById(dto.getId());
				if(null == mortRecord){
					returnMap.put("returnCode", "00000");
					returnMap.put("returnMsg", "按揭记录不存在");
					return returnMap;
				}
			}else{
				returnMap.put("returnCode", "00000");
				returnMap.put("returnMsg", "按揭记录不存在");
				return returnMap;
			}
			try {
				String ext_completeDate = dto.getExt_completeDate();
				String ext_expectLoadDate = dto.getExt_expectLoadDate();
				if(StringUtils.isNotEmpty(ext_completeDate)){
					dto.setCompleteDate(sdf.parse(ext_completeDate));
				}
				if(StringUtils.isNotEmpty(ext_expectLoadDate)){
					dto.setExpectLoadDate(sdf.parse(ext_expectLoadDate));
				}
			} catch (ParseException e) {
				e.printStackTrace();
				returnMap.put("returnCode", "00000");
				returnMap.put("returnMsg", "日期错误");
				return returnMap;
			}
			
			dto.setProcessStatus(ProcessStatusEnum.YES.getNo());
			dto.setUpdateUserId(dto.getUserId());
			service.update(dto);
			
			//添加按揭跟进记录
			MortgageRecordFollowDto mrfDto = new MortgageRecordFollowDto();
			mrfDto.setMortgageRecordId(dto.getId());
			if(StringUtils.isNotEmpty(mortRecord.getProgressLoan())){
				mrfDto.setOldProgressLoan(mortRecord.getProgressLoan());
			}else{
				mrfDto.setOldProgressLoan(dto.getProgressLoan());
			}
			mrfDto.setNowProgressLoan(dto.getProgressLoan());
			mrfDto.setRemark(dto.getRemark());
			mrfDto.setMerchantId(mortRecord.getMerchantId());
			mrfDto.setAccessCode(mortRecord.getAccessCode());
			mrfDto.setUserCode(dto.getUserCode());
			mrfDto.setCreateUserId(dto.getUserId());
			mrfDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			mrfDto = mortgageRecordFollowService.create(mrfDto);
			
			//存储收款凭证
			long mrfId = dto.getId();
			String imgType = "";
			String remark = "";
			String fileArr = dto.getFileArr();
			imgType = ImgTypeEnum.MORTGAGE.getNo();
			remark = "按揭凭证";
			if(StringUtils.isNotEmpty(fileArr)){
				String fileArrList[] = fileArr.split("[|]");
				for(String file: fileArrList){
					if(StringUtils.isNotEmpty(file)){
						ImageDto imageDto = new ImageDto();
						imageDto.setObjectId(mrfId);
						imageDto.setTitle("按揭凭证");
						imageDto.setContent("按揭凭证");
						imageDto.setSmallUrl(file);
						imageDto.setImgType(imgType);
						imageDto.setMerchantId(mrfDto.getMerchantId());
						imageDto.setUserCode(mrfDto.getUserCode());
						imageDto.setAccessCode(mrfDto.getAccessCode());
						imageDto.setRemark(remark);
						imageDto.setCreateUserId(mrfDto.getCreateUserId());
						imageDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
						imageService.create(imageDto);
					}
				}
			}
			
			returnMap.put("returnCode", "00001");
			returnMap.put("returnMsg", "保存成功");
		}catch(Exception ex){
			ex.printStackTrace();
			returnMap.put("returnCode", "00000");
			returnMap.put("returnMsg", "系统异常,请联系管理员!");
			return returnMap;
		}
		return returnMap;
		
	}

}
